package leetcode.tree;

/**
 * @author wangmaolin1
 * @date 2021/12/29 下午10:26
 */
public class _235二叉搜索树的最近公共祖先 {

    /**
     * 递归
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        int max = Math.max(p.val, q.val);
        int min = Math.min(p.val, q.val);
        if (max < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        }
        if (min > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        }
        return root;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        int max = Math.max(p.val, q.val);
        int min = Math.min(p.val, q.val);
        TreeNode temp = root;
        while (true) {
            if (max < temp.val) {
                temp = temp.left;
            } else if (min > temp.val) {
                temp = temp.right;
            } else {
                break;
            }
        }
        return temp;
    }

}
